const db=require('../db/index.js')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')
const login= (req, res) => {
  const user = req.body;
  const userNameRegex = /^[a-zA-Z0-9]{1,10}$/;
  const passwordRegex = /^\d{8}$/;
  if (!user.userName || !user.password) {
    return res.send({
      status: 400,
      message: '用户名或密码不能为空'
    });
  }else if(!userNameRegex.test(user.userName)){
    return res.send({
      status: 400,
      message: '用户名必须由不超过十个的字母数字组成'
    });
  }else if(!passwordRegex.test(user.password)){
    return res.send({
      status: 400,
      message: '密码必须是8位数字'
    });
  }

  const sql = `select * from new_users where userName=?`;
  db.query(sql, [user.userName], (err, result) => {
    if (err) {
      return res.send({
        status: 500,
        message: err.message
      });
    }

    if (result.length !== 1) {
      return res.send({
        status: 404,
        message: '用户名不存在'
      });
    }
    // 密码校验操作
    if (!bcrypt.compareSync(user.password, result[0].password)) {
      return res.send({
        status: 400,
        message: '密码错误'
      });
    }
    const userData = {...result[0],password:''}
    const token = jwt.sign(userData, config.jwtSecretKey, { expiresIn: config.expiresIn });

    return res.send({
      status: 200,
      message: '登录成功',
      token:"Bearer "+token,
      userId:userData.id,
      addNum:userData.addNum
    });

  })
}
const phoneLogin=(req,res)=>{
  const user = req.body
  const phoneRegex = /^1[3-9]\d{9}$/;
  if(!user.phone){
    return res.send({
      status: 400,
      message: '手机号不能为空'
    });
  }
  else if(!phoneRegex.test(user.phone)){
    return res.send({
      status: 400,
      message: '手机号格式不正确'
    });
  }
  if (user.msgCaptcha === '') {
    this.$toast.fail('验证码不能为空')
  }
  const msgCaptchaRegex = /^\d{4}$/
  if (!msgCaptchaRegex.test(user.msgCaptcha)) {
    this.$toast.fail('请输入正确的验证码')
  }

  const sql = `select * from new_users where phone=?`;
  db.query(sql, [user.phone], (err, result) => {
    if (err) {
      return res.send({
        status: 500,
        message: err.message
      });
    }
    const userData = {...result[0],password:''}
    if (result.length !== 1) {
      return res.send({
        status: 404,
        message: '手机号不存在'
      });
    }else if(user.msgCaptcha!==result[0].code){
      return res.send({
        status: 400,
        message: '验证码错误'
      });
    }
   
    const token = jwt.sign(userData, config.jwtSecretKey, { expiresIn: config.expiresIn });

    return res.send({
      status: 200,
      message: '登录成功',
      token:"Bearer "+token,
      userId:userData.id,
      addNum:userData.addNum
    });
})

}
const register = (req, res) => {
  const userNameRegex = /^[a-zA-Z0-9]{1,10}$/;
  const passwordRegex = /^\d{8}$/;
  const phoneRegex = /^1[3-9]\d{9}$/;
  const user = req.body;
  if (!user.userName || !user.password||!user.phone) {
    return res.send({
      status: 400,
      message: '用户名或密码或手机号不能为空'
    });
  }else if(!userNameRegex.test(user.userName)){
    return res.send({
      status: 400,
      message: '用户名必须由不超过十个的字母数字组成'
    });
  }else if(!passwordRegex.test(user.password)){
    return res.send({
      status: 400,
      message: '密码必须是8位数字'
    });
  }else if(!phoneRegex.test(user.phone)){
    return res.send({
      status: 400,
      message: '手机号格式不正确'
    });
  }

  const sql = `select * from new_users where userName=?`;
  db.query(sql, [user.userName], (err, result) => {
    if (err) {
      return res.send({
        status: 500,
        message: err.message
      });
    }

    if (result.length > 0) {
      return res.send({
        status: 400,
        message: '用户名已存在'
      });
    }

    // 密码加密操作
    user.password = bcrypt.hashSync(user.password, 10);
    const sql2 = `insert into new_users set ?`;
    const price=100000;
    db.query(sql2, { userName: user.userName, password: user.password ,phone:user.phone,price:price}, (err, result) => {
      if (err) {
        return res.send({
          status: 500,
          message: err.message
        });
      }

      if (result.affectedRows !== 1) {
        return res.send({
          status: 500,
          message: '注册失败'
        });
      }

      // 注册成功
      return res.send({
        status: 200,
        message: '注册成功'
      });
    });
  });
};
const getMsgCaptcha = (req, res) => {
  const user = req.body;
  
  console.log(user);
  const phoneRegex = /^1[3-9]\d{9}$/;

  if (!user.phone) {
    return res.send({
      status: 400,
      message: '手机号不能为空'
    });
  } else if (!phoneRegex.test(user.phone)) {
    return res.send({
      status: 400,
      message: '手机号格式不正确'
    });
  }
  //检查电话号码是否已经存在在数据库中
    const checkPhoneQuery = 'SELECT * FROM new_users WHERE phone = ?';
    db.query(checkPhoneQuery, [user.phone], (err, result) => {
      if (err) {
        console.error("数据库操作出错: ", err.message);
        return res.send({
          status: 500,
          message: err.message
        });
      }
  
      if (result.length <= 0) {
        // 如果电话号码已经存在
        return res.send({
          status: 404,
          message: '该手机号未注册'
        });
      }
          // 检查请求次数是否超过限制(五分钟最多申请三次验证码请求)
      const requestLimit = 3;  // 每五分钟最多请求次数
      const timeLimit = 5 * 60 * 1000; // 1小时（毫秒）

      const checkRequestCountQuery = 'SELECT * FROM new_users WHERE phone = ?';
      db.query(checkRequestCountQuery, [user.phone], (err, result) => {
        if (err) {
          console.error("数据库操作出错: ", err.message);
          return res.send({
            status: 500,
            message: err.message
          });
        }

        const now = Date.now();

        if (result.length > 0) {
          const record = result[0];
          const lastRequestTime = new Date(record.lastTime).getTime();

          // 如果上次请求时间在五分钟内且请求次数达到限制，拒绝请求
          if (now - lastRequestTime < timeLimit && record.count >= requestLimit) {
            return res.send({
              status: 400,
              message: '请求次数超过限制，请稍后再试'
            });
          }

          // 更新请求次数和时间
          const newRequestCount = (now - lastRequestTime < timeLimit) ? record.count + 1 : 1;
          const updateRequestLogQuery = 'UPDATE new_users SET count = ?, lastTime = NOW() WHERE phone = ?';
          db.query(updateRequestLogQuery, [newRequestCount, user.phone], (err, result) => {
            if (err) {
              console.error("数据库操作出错: ", err.message);
              return res.send({
                status: 500,
                message: err.message
              });
            }

            sendCaptcha(user, res);
          });

        } else {
          // 如果是第一次请求，插入新记录
          const insertRequestLogQuery = 'INSERT INTO new_users (phone, count, lastTime) VALUES (?, ?, NOW())';
          db.query(insertRequestLogQuery, [user.phone, 1], (err, result) => {
            if (err) {
              console.error("数据库操作出错3:", err.message);
              return res.send({
                status: 500,
                message: err.message
              });
            }

            sendCaptcha(user, res);
          });
        }
      });
        });
  
};
// 发送验证码的函数，不做接口
const sendCaptcha = (user, res) => {
  const captcha = Math.floor(Math.random() * 9000) + 1000;
  //检查数据库中是否已存在该电话号码的验证码记录
  const checkPhoneQuery = 'SELECT COUNT(*) AS count FROM new_users WHERE phone = ?';
  db.query(checkPhoneQuery, [user.phone], (err, result) => {
    if (err) {
      console.error("数据库操作出错:", err.message);
      return res.send({
        status: 500,
        message: err.message
      });
    }

    if (result[0].count > 0) {
      const updateCaptchaQuery = 'UPDATE new_users SET code = ? WHERE phone = ?';
      db.query(updateCaptchaQuery, [captcha, user.phone], (err, result) => {
        if (err) {
          console.error("数据库操作出错:", err.message);
          return res.send({
            status: 500,
            message: err.message
          });
        }

        console.log('验证码已更新:', captcha);
        return res.send({
          status: 200,
          message: '验证码已发送',
          code: captcha
        });
      });
    } else {
      const insertCaptchaQuery = 'INSERT INTO new_users (phone, code) VALUES (?, ?)';
      db.query(insertCaptchaQuery, [user.phone, captcha], (err, result) => {
        if (err) {
          console.error("Database error:", err.message);
          return res.send({
            status: 500,
            message: err.message
          });
        }

        console.log('验证码已发送:', captcha);
        return res.send({
          status: 200,
          message: '验证码已发送',
          code: captcha
        });
      });
    }
  });
};
module.exports = {
  login,
  register,
  phoneLogin,
  getMsgCaptcha
}